package club.web51.classroom_tool.Services;

import club.web51.classroom_tool.DO.collDO.Clazz;
import club.web51.classroom_tool.DO.sysDO.Msg;
import club.web51.classroom_tool.Enums.MsgEnum;
import club.web51.classroom_tool.Exceptions.ErrDataException;
import club.web51.classroom_tool.Repositories.ClazzRepository;
import club.web51.classroom_tool.Utils.BeanPlusUtils;
import club.web51.classroom_tool.Utils.MsgUtil;
import club.web51.classroom_tool.Utils.ObjectUtil;
import club.web51.classroom_tool.Utils.SFWhere;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 服务类
 * @author yln
 * @since 1.0.0
 */
@Service
public class ClazzService {
    @Resource
    ClazzRepository clazzRepository;
    @Resource
    UserService userService;
    /**
     * 根据Clazz的字段自动生成条件,字段值为null不生成条件
     * 如果是数值型的字段,前端不传入值,默认是0,例如ID的类型是Long,如果不传值,默认是0
     * 可以自己设置下SFWhere.and(clazz).equal(实体.getId()>0,"id",实体.getId()).build()
     * @param clazz     实体对象
     * @param pageable 分页对象
     * @return 返回分页\状态码
     */
    public ResponseEntity<Object> search(Clazz clazz, Pageable pageable) {
        Page<Clazz> all = clazzRepository.findAll(SFWhere.and(clazz)
                //.in(true, "userName", longs)
//                .equal(!字段值的判断.equals("") && 字段值的判断 != null, "字段名称", 字段值)
                .like(clazz.getName() != null, "name", "%" + clazz.getName() + "%")
                //....
                .build(), pageable);
        return new ResponseEntity<>(all, HttpStatus.OK);
    }

    public Msg updateOne(Clazz clazz){
        if(ObjectUtil.isNull(clazz)){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }
        if(ObjectUtil.isNull(clazz.getId())){
            clazzRepository.save(clazz);
            return MsgUtil.success();
        }
        Clazz clazz1 = clazzRepository.getOne(clazz.getId());
        BeanPlusUtils.copyPropertiesIgnoreNull(clazz,clazz1);
        clazzRepository.save(clazz1);
        return MsgUtil.success();
    }

    public Msg deleteOne(Long id){

        if(ObjectUtil.isNull(id)){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EMPTY);
        }

        clazzRepository.deleteById(id);
        return MsgUtil.success();
    }
}
